import { Card, CardPattern, CardCombination, CardRank, CardSuit } from '../types/card'
import { sortCardsByPower, isLevelCard as isLevelCardUtil, isMatchingCard as isMatchingCardUtil } from './cardUtils'

/**
 * 识别牌型
 * @param cards 要识别的牌
 * @param levelCard 级牌（可选，用于逢人配）
 */
export function identifyCardPattern(cards: Card[], levelCard?: Card | null): CardCombination {
  if (cards.length === 0) {
    return {
      type: CardPattern.PASS,
      cards: [],
      power: 0
    }
  }

  const sortedCards = sortCardsByPower(cards)
  const cardCount = cards.length

  console.log('identifyCardPattern开始:', {
    cardCount,
    levelCard: levelCard ? `${levelCard.suit}-${levelCard.rank}` : 'null',
    cards: sortedCards.map(c => `suit:${c.suit} rank:${c.rank}`),
    cardIds: sortedCards.map(c => c.id)
  })

  // 掼蛋规则：除了炸弹，最多只能出6张牌
  if (cardCount > 6) {
    // 检查是否为炸弹（所有牌面值相同）
    if (!areAllSameRank(sortedCards, levelCard)) {
      // 不是炸弹且超过6张，无效牌型
      return {
        type: CardPattern.PASS,
        cards: sortedCards,
        power: 0
      }
    }
  }

  // 单张
  if (cardCount === 1) {
    return {
      type: CardPattern.SINGLE,
      cards: sortedCards,
      power: calculateSinglePower(sortedCards[0], levelCard)
    }
  }

  // 对子
  if (cardCount === 2 && areAllSameRank(sortedCards, levelCard)) {
    return {
      type: CardPattern.PAIR,
      cards: sortedCards,
      power: calculatePairPower(getMaxNonLevelCard(sortedCards, levelCard), levelCard)
    }
  }

  // 刻子 (三张相同)
  if (cardCount === 3 && areAllSameRank(sortedCards, levelCard)) {
    return {
      type: CardPattern.TRIPLE,
      cards: sortedCards,
      power: calculateTriplePower(getMaxNonLevelCard(sortedCards, levelCard), levelCard)
    }
  }

  // 5张牌的牌型检测（优先级：五炸 > 三带二 > 同花顺 > 顺子）
  if (cardCount === 5) {
    console.log('开始检测5张牌牌型')

    // 五炸检测 (最高优先级 - 所有牌相同)
    if (areAllSameRank(sortedCards, levelCard)) {
      console.log('✓ 识别为五炸')
      return {
        type: CardPattern.FIVE_BOMB,
        cards: sortedCards,
        power: calculateBombPower(getMaxNonLevelCard(sortedCards, levelCard), 5, levelCard)
      }
    }

    // 三带二检测 (第二优先级 - 避免被误判为顺子)
    const tripleWithPair = checkTripleWithPairWithLevel(sortedCards, levelCard)
    if (tripleWithPair) {
      console.log('✓ 识别为三带二')
      return tripleWithPair
    }

    // 同花顺检测 (第三优先级)
    const isSameSuit = isSameSuitStraight(sortedCards, levelCard)
    console.log('同花顺检测结果:', isSameSuit)
    if (isSameSuit) {
      console.log('✓ 识别为同花顺')
      return {
        type: CardPattern.SAME_SUIT_STRAIGHT,
        cards: sortedCards,
        power: calculateSameSuitStraightPower(sortedCards, levelCard)
      }
    }

    // 顺子检测 (第四优先级)
    const isStraightResult = isStraight(sortedCards, levelCard)
    console.log('顺子检测结果:', isStraightResult)
    if (isStraightResult) {
      console.log('✓ 识别为顺子')
      return {
        type: CardPattern.STRAIGHT,
        cards: sortedCards,
        power: calculateStraightPower(sortedCards, levelCard)
      }
    }
  }

  // 6张牌的特殊牌型检测
  if (cardCount === 6) {
    // 先检查钢板 (两个连续三张，如 333444、888999)
    const steelBoard = checkSteelBoardWithLevel(sortedCards, levelCard)
    if (steelBoard) {
      console.log('识别为钢板:', steelBoard)
      return {
        ...steelBoard,
        type: CardPattern.STEEL_BOARD
      }
    }

    // 再检查木板 (三个连续对子，如 778899)
    const woodBoard = checkWoodBoardWithLevel(sortedCards, levelCard)
    if (woodBoard) {
      console.log('识别为木板:', woodBoard)
      return {
        ...woodBoard,
        type: CardPattern.WOOD_BOARD
      }
    }

    console.log('6张牌未识别为钢板或木板')
  }

  // 炸弹检测（4张、6张及以上）
  if (cardCount >= 4 && cardCount !== 5 && areAllSameRank(sortedCards, levelCard)) {
    const bombType = getBombType(cardCount)
    console.log('识别为炸弹:', bombType)
    return {
      type: bombType,
      cards: sortedCards,
      power: calculateBombPower(getMaxNonLevelCard(sortedCards, levelCard), cardCount, levelCard)
    }
  }

  // 未识别的牌型
  return {
    type: CardPattern.PASS,
    cards: sortedCards,
    power: 0
  }
}

/**
 * 检查牌是否为级牌
 */
// 使用从cardUtils导入的isLevelCard函数
function isLevelCard(card: Card, levelCard: Card | null | undefined): boolean {
  return isLevelCardUtil(card, levelCard)
}

/**
 * 检查牌是否为配牌（逢人配）
 * 掼蛋规则：只有红桃的级牌可以作为配牌（通配牌）
 * 使用从cardUtils导入的isMatchingCard函数
 */
function isMatchingCard(card: Card, levelCard: Card | null | undefined): boolean {
  return isMatchingCardUtil(card, levelCard ?? null)
}

/**
 * 检查牌是否为通配牌
 * 通配牌包括：
 * 1. 所有花色的级牌（但只有红桃级牌可以配牌）
 * 2. 红桃的级牌（逢人配）
 *
 * 注意：非红桃的级牌虽然是级牌，但不能配牌，只能和相同点数的牌组合
 */
function isWildcard(card: Card, levelCard: Card | null | undefined): boolean {
  // 只有红桃的级牌才能作为通配牌
  return isMatchingCard(card, levelCard)
}

/**
 * 获取非通配牌中最大的牌（用于计算级牌/配牌后的牌力）
 * 如果全是通配牌，返回最后一张（最大的）
 */
function getMaxNonLevelCard(cards: Card[], levelCard: Card | null | undefined): Card {
  if (cards.length === 0) {
    throw new Error('没有卡牌')
  }

  // 过滤出非通配牌（既不是级牌也不是配牌）
  const nonWildcards = cards.filter(card => !isWildcard(card, levelCard))

  // 如果全是通配牌，使用最后一张（sortedCards已排序，最后一张最大）
  if (nonWildcards.length === 0) {
    return cards[cards.length - 1]
  }

  // 返回非通配牌中最大的（sortedCards已排序，最后一张最大）
  return nonWildcards[nonWildcards.length - 1]
}

/**
 * 检查所有牌是否为相同面值（考虑级牌和配牌）
 * 掼蛋规则：
 * 1. 所有花色的级牌都是级牌，可以和相同点数组合
 * 2. 只有红桃级牌可以配任意牌（逢人配）
 */
function areAllSameRank(cards: Card[], levelCard?: Card | null): boolean {
  if (cards.length === 0) return false

  // 分离红桃级牌（可以配牌）和其他牌
  const wildcards = cards.filter(card => isWildcard(card, levelCard)) // 只有红桃级牌
  const nonWildcards = cards.filter(card => !isWildcard(card, levelCard))

  console.log('areAllSameRank检查:', {
    totalCards: cards.length,
    levelCard: levelCard ? `${levelCard.suit}-${levelCard.rank}` : 'null',
    wildcardsCount: wildcards.length,
    nonWildcardsCount: nonWildcards.length,
    nonWildcardRanks: nonWildcards.map(c => `${c.suit}-${c.rank}`),
    wildcards: wildcards.map(c => `${c.suit}-${c.rank}`)
  })

  if (nonWildcards.length === 0) {
    // 全是红桃级牌（通配牌），算作相同
    console.log('全是红桃级牌（通配牌），返回true')
    return true
  }

  // 检查非通配牌是否都是相同点数
  // 注意：非红桃的级牌也算作普通牌，需要和其他牌点数相同
  const firstRank = nonWildcards[0].rank
  const result = nonWildcards.every(card => card.rank === firstRank)
  console.log('非通配牌检查结果:', result, '第一张rank:', firstRank)
  return result
}

/**
 * 获取各面值的数量统计
 */
function getRankCounts(cards: Card[]): Record<CardRank, number> {
  const counts: Record<CardRank, number> = {} as Record<CardRank, number>
  cards.forEach(card => {
    counts[card.rank] = (counts[card.rank] || 0) + 1
  })
  return counts
}

/**
 * 检查是否为顺子
 * 掼蛋规则：顺子必须是5张
 */
function isStraight(cards: Card[], levelCard?: Card | null): boolean {
  // 掼蛋规则：顺子必须是5张
  if (cards.length !== 5) return false

  // 排除大小王
  const normalCards = cards.filter(card =>
    card.suit !== CardSuit.SMALL_JOKER && card.suit !== CardSuit.BIG_JOKER
  )

  if (normalCards.length !== cards.length) return false

  // 分离通配牌（级牌和配牌）和非通配牌
  const wildcards = normalCards.filter(card => isWildcard(card, levelCard))
  const nonWildcards = normalCards.filter(card => !isWildcard(card, levelCard))

  console.log('顺子检测:', {
    totalCards: normalCards.length,
    wildcardsCount: wildcards.length,
    nonWildcardsCount: nonWildcards.length,
    nonWildcardRanks: nonWildcards.map(c => c.rank).sort((a, b) => a - b),
    wildcards: wildcards.map(c => `${c.suit}-${c.rank}`)
  })

  // 如果没有通配牌，使用原来的逻辑
  if (wildcards.length === 0) {
    const sortedCards = sortCardsByPower(normalCards)

    // 检查是否为A-2-3-4-5的特殊顺子
    const ranks = sortedCards.map(c => c.rank).sort((a, b) => a - b)
    const isA2345 = ranks[0] === CardRank.TWO &&
      ranks[1] === CardRank.THREE &&
      ranks[2] === CardRank.FOUR &&
      ranks[3] === CardRank.FIVE &&
      ranks[4] === CardRank.ACE

    if (isA2345) {
      console.log('识别为A-2-3-4-5顺子')
      return true
    }

    // 检查普通顺子（连续递增）
    for (let i = 1; i < sortedCards.length; i++) {
      console.log(`检查连续性: ${sortedCards[i - 1].rank} -> ${sortedCards[i].rank}`)
      if (sortedCards[i].rank !== sortedCards[i - 1].rank + 1) {
        console.log('不连续，不是顺子')
        return false
      }
    }
    console.log('连续，是顺子')
    return true
  }

  // 有通配牌的情况：尝试用通配牌填补空缺
  if (nonWildcards.length === 0) {
    // 全是通配牌，可以组成顺子
    console.log('全是通配牌，可以组成顺子')
    return true
  }

  const nonWildcardRanks = nonWildcards.map(c => c.rank).sort((a, b) => a - b)
  const minRank = nonWildcardRanks[0]
  const maxRank = nonWildcardRanks[nonWildcardRanks.length - 1]

  // 优先处理特殊情况：A-2-3-4-5（允许通配牌参与配成该顺子）
  // 规则：非通配牌如果都属于 {2,3,4,5,A}，且缺失的张数不超过通配牌数量，则可以组成该顺子
  const lowStraightSet = [CardRank.TWO, CardRank.THREE, CardRank.FOUR, CardRank.FIVE, CardRank.ACE]
  const nonWildcardAllInLowSet = nonWildcardRanks.every(r => lowStraightSet.includes(r))
  if (nonWildcardAllInLowSet) {
    const nonWildcardSet = new Set(nonWildcardRanks)
    const missingCount = lowStraightSet.filter(r => !nonWildcardSet.has(r)).length
    if (missingCount <= wildcards.length) {
      console.log('通配牌可以配成A-2-3-4-5顺子')
      return true
    }
  }

  // 检查是否可以用通配牌填补成顺子
  // 顺子的跨度不能超过 (非通配牌数量 + 通配牌数量 - 1)
  const span = maxRank - minRank + 1
  const totalCards = nonWildcards.length + wildcards.length

  if (span > totalCards) {
    console.log('跨度太大，无法组成顺子')
    return false
  }

  // 检查非通配牌之间的空缺是否可以用通配牌填补
  let gapsCount = 0
  for (let i = 1; i < nonWildcardRanks.length; i++) {
    gapsCount += nonWildcardRanks[i] - nonWildcardRanks[i - 1] - 1
  }

  // 还需要填补到5张牌的空缺
  const totalGaps = span - nonWildcards.length

  if (totalGaps <= wildcards.length) {
    console.log('通配牌可以填补空缺，组成顺子')
    return true
  }

  // 特殊情况：A-2-3-4-5顺子（A可以在最前面）
  if (nonWildcardRanks.includes(CardRank.ACE)) {
    // 尝试将A作为最小的牌
    const ranksWithoutAce = nonWildcardRanks.filter(r => r !== CardRank.ACE)
    if (ranksWithoutAce.length > 0) {
      const minWithoutAce = ranksWithoutAce[0]
      const maxWithoutAce = ranksWithoutAce[ranksWithoutAce.length - 1]

      // 检查是否可以组成A-2-3-4-5
      if (minWithoutAce >= CardRank.TWO && maxWithoutAce <= CardRank.FIVE) {
        const spanA2345 = maxWithoutAce - CardRank.TWO + 2 // +2 因为包括A和最大牌
        const gapsA2345 = spanA2345 - nonWildcards.length
        if (gapsA2345 <= wildcards.length) {
          console.log('通配牌可以填补A-2-3-4-5顺子')
          return true
        }
      }
    }
  }

  console.log('无法组成顺子')
  return false
}

/**
 * 检查是否为同花顺
 * 掼蛋规则：同花顺必须是5张
 */
function isSameSuitStraight(cards: Card[], levelCard?: Card | null): boolean {
  // 掼蛋规则：同花顺必须是5张
  if (cards.length !== 5) return false

  // 先检查是否为顺子
  if (!isStraight(cards, levelCard)) return false

  // 分离通配牌（级牌和配牌）和非通配牌
  const wildcards = cards.filter(card => isWildcard(card, levelCard))
  const nonWildcards = cards.filter(card => !isWildcard(card, levelCard))

  // 如果没有非通配牌，全是通配牌，可以组成同花顺
  if (nonWildcards.length === 0) {
    console.log('全是通配牌，可以组成同花顺')
    return true
  }

  // 检查非通配牌是否同花色（通配牌可以配任意花色）
  const firstSuit = nonWildcards[0].suit
  const allSameSuit = nonWildcards.every(card => card.suit === firstSuit)

  console.log('同花顺检测:', {
    allSameSuit,
    firstSuit,
    wildcardsCount: wildcards.length
  })

  return allSameSuit
}

/**
 * 根据炸弹数量获取炸弹类型
 */
function getBombType(count: number): CardPattern {
  switch (count) {
    case 4: return CardPattern.FOUR_BOMB
    case 5: return CardPattern.FIVE_BOMB
    case 6: return CardPattern.SIX_BOMB
    case 7: return CardPattern.SEVEN_BOMB
    case 8: return CardPattern.EIGHT_BOMB
    case 9: return CardPattern.NINE_BOMB
    case 10: return CardPattern.TEN_BOMB
    default: return CardPattern.FOUR_BOMB
  }
}

/**
 * 计算单张牌力
 * @param card 要计算的牌
 * @param levelCard 级牌（用于判断级牌大小）
 */
function calculateSinglePower(card: Card, levelCard?: Card | null): number {
  // 大王最大
  if (card.suit === CardSuit.BIG_JOKER) return 1000
  // 小王第二大
  if (card.suit === CardSuit.SMALL_JOKER) return 999

  // 如果有级牌，级牌比普通牌大，但比王小
  if (levelCard && card.rank === levelCard.rank) {
    // 级牌的牌力设置为998（比小王小，比A大）
    return 998
  }

  // 普通牌按rank值计算
  // 如果当前牌的rank大于级牌的rank，需要调整（因为级牌插入到了A和小王之间）
  if (levelCard && card.rank > levelCard.rank) {
    // 这些牌的实际牌力需要降低，因为级牌比它们大
    return card.rank
  }

  return card.rank
}

/**
 * 计算对子牌力
 */
function calculatePairPower(card: Card, levelCard?: Card | null): number {
  return calculateSinglePower(card, levelCard) + 100
}

/**
 * 计算刻子牌力
 */
function calculateTriplePower(card: Card, levelCard?: Card | null): number {
  return calculateSinglePower(card, levelCard) + 200
}

/**
 * 计算三带二牌力
 * 需要考虑级牌配牌的情况
 */
function calculateTripleWithPairPower(cards: Card[], levelCard?: Card | null): number {
  const rankCounts = getRankCounts(cards)
  let tripleRank: CardRank | null = null

  // 找到三张相同的牌
  for (const [rank, count] of Object.entries(rankCounts)) {
    if (count === 3) {
      tripleRank = parseInt(rank) as CardRank
      break
    }
  }

  // 如果没有找到三张（可能是级牌配出来的）
  if (tripleRank === null) {
    // 找出现次数最多的非级牌
    const nonLevelCards = cards.filter(card => !isLevelCard(card, levelCard))
    if (nonLevelCards.length > 0) {
      const nonLevelRankCounts = getRankCounts(nonLevelCards)
      let maxCount = 0
      for (const [rank, count] of Object.entries(nonLevelRankCounts)) {
        if (count > maxCount) {
          maxCount = count
          tripleRank = parseInt(rank) as CardRank
        }
      }
    }
  }

  if (tripleRank !== null) {
    return tripleRank + 300
  }
  return 300
}

/**
 * 计算炸弹牌力
 */
function calculateBombPower(card: Card, count: number, levelCard?: Card | null): number {
  const basePower = calculateSinglePower(card, levelCard)
  return basePower + 500 + (count - 4) * 100
}

/**
 * 计算顺子牌力
 */
function calculateStraightPower(cards: Card[], levelCard?: Card | null): number {
  // 检查是否为A-2-3-4-5顺子
  const ranks = cards.map(c => c.rank).sort((a, b) => a - b)
  const isA2345 = ranks[0] === CardRank.TWO &&
    ranks[1] === CardRank.THREE &&
    ranks[2] === CardRank.FOUR &&
    ranks[3] === CardRank.FIVE &&
    ranks[4] === CardRank.ACE

  if (isA2345) {
    // A-2-3-4-5是最小的顺子，基础牌力为5（最大牌是5）
    // 顺子基础分400，加上5的牌力
    console.log('计算A-2-3-4-5顺子牌力: 400 + CardRank.FIVE =', 400 + CardRank.FIVE)
    return 400 + CardRank.FIVE
  }

  // 其他顺子：使用最大牌的牌力
  const sortedCards = sortCardsByPower(cards)
  const highestCard = sortedCards[sortedCards.length - 1]
  const power = 400 + calculateSinglePower(highestCard, levelCard)
  console.log('计算顺子牌力: 400 + 最大牌牌力 =', power)
  return power
}

/**
 * 计算同花顺牌力
 */
function calculateSameSuitStraightPower(cards: Card[], levelCard?: Card | null): number {
  // 检查是否为A-2-3-4-5同花顺
  const ranks = cards.map(c => c.rank).sort((a, b) => a - b)
  const isA2345 = ranks[0] === CardRank.TWO &&
    ranks[1] === CardRank.THREE &&
    ranks[2] === CardRank.FOUR &&
    ranks[3] === CardRank.FIVE &&
    ranks[4] === CardRank.ACE

  if (isA2345) {
    // A-2-3-4-5是最小的同花顺，基础牌力为5（最大牌是5）
    // 同花顺基础分500，加上5的牌力
    console.log('计算A-2-3-4-5同花顺牌力: 500 + CardRank.FIVE =', 500 + CardRank.FIVE)
    return 500 + CardRank.FIVE
  }

  // 其他同花顺：使用最大牌的牌力
  const sortedCards = sortCardsByPower(cards)
  const highestCard = sortedCards[sortedCards.length - 1]
  const power = 500 + calculateSinglePower(highestCard, levelCard)
  console.log('计算同花顺牌力: 500 + 最大牌牌力 =', power)
  return power
}

/**
 * 比较两个牌型的大小
 */
export function compareCardCombinations(combo1: CardCombination, combo2: CardCombination): number {
  // 炸弹类型优先级最高
  const isBomb1 = combo1.type >= CardPattern.FOUR_BOMB
  const isBomb2 = combo2.type >= CardPattern.FOUR_BOMB

  if (isBomb1 && !isBomb2) return 1
  if (!isBomb1 && isBomb2) return -1

  // 相同类型比较牌力
  if (combo1.type === combo2.type) {
    return combo1.power - combo2.power
  }

  // 不同类型，炸弹最大
  if (isBomb1 && isBomb2) {
    return combo1.power - combo2.power
  }

  // 其他情况返回0 (不可比较)
  return 0
}

/**
 * 验证出牌是否合法
 * 简化版：只验证牌型是否有效，不比较大小（由玩家自己判断）
 */
export function validatePlay(cards: Card[], _lastPlay: CardCombination | null, levelCard?: Card | null): boolean {
  if (cards.length === 0) return true // 过牌总是合法的

  const currentPlay = identifyCardPattern(cards, levelCard)

  console.log('validatePlay检查:', {
    cardCount: cards.length,
    currentType: currentPlay.type,
    isValidPattern: currentPlay.type !== CardPattern.PASS
  })

  // 只要能识别出有效牌型，就允许出牌
  if (currentPlay.type === CardPattern.PASS && cards.length > 0) {
    console.log('无效牌型，拒绝出牌')
    return false
  }

  console.log('有效牌型，允许出牌')
  return true
}/**
 * 检查三带二 (掼蛋规则)
 */
function checkTripleWithPair(cards: Card[], levelCard?: Card | null): CardCombination | null {
  if (cards.length !== 5) return null

  const rankCounts = getRankCounts(cards)
  const counts = Object.values(rankCounts)

  if (counts.includes(3) && counts.includes(2)) {
    return {
      type: CardPattern.TRIPLE_WITH_PAIR,
      cards,
      power: calculateTripleWithPairPower(cards, levelCard)
    }
  }

  return null
}

/**
 * 检查三带二 (支持级牌配牌)
 */
function checkTripleWithPairWithLevel(cards: Card[], levelCard?: Card | null): CardCombination | null {
  if (cards.length !== 5) return null

  // 分离通配牌（级牌和配牌）和非通配牌
  const wildcards = cards.filter(card => isWildcard(card, levelCard))
  const nonWildcards = cards.filter(card => !isWildcard(card, levelCard))

  // 如果没有通配牌，使用普通检测
  if (wildcards.length === 0) {
    return checkTripleWithPair(cards, levelCard)
  }

  // 统计非通配牌的数量
  const rankCounts = getRankCounts(nonWildcards)
  const counts = Object.values(rankCounts).sort((a, b) => b - a)

  // 通配牌可以配成三带二的各种情况：
  // 1. 已有3张+1张，通配牌配成对子 (3+1+1通配)
  // 2. 已有2张+2张，通配牌配成三张 (2+2+1通配)
  // 3. 已有2张+1张，2个通配牌配成三张或对子 (2+1+2通配)
  // 4. 其他情况用通配牌补齐

  const wildcardCount = wildcards.length

  if (wildcardCount === 1) {
    // 1个通配牌：需要已有3+1或2+2
    if (counts.length === 2 && ((counts[0] === 3 && counts[1] === 1) || (counts[0] === 2 && counts[1] === 2))) {
      return {
        type: CardPattern.TRIPLE_WITH_PAIR,
        cards,
        power: calculateTripleWithPairPower(cards, levelCard)
      }
    }
  } else if (wildcardCount === 2) {
    // 2个通配牌：需要已有2+1或3+0
    if (counts.length >= 1) {
      if ((counts.length === 2 && counts[0] === 2 && counts[1] === 1) ||
        (counts.length === 1 && counts[0] === 3)) {
        return {
          type: CardPattern.TRIPLE_WITH_PAIR,
          cards,
          power: calculateTripleWithPairPower(cards, levelCard)
        }
      }
    }
  } else if (wildcardCount === 3) {
    // 3个通配牌：需要已有2张相同
    if (counts.length === 1 && counts[0] === 2) {
      return {
        type: CardPattern.TRIPLE_WITH_PAIR,
        cards,
        power: calculateTripleWithPairPower(cards, levelCard)
      }
    }
  } else if (wildcardCount === 4) {
    // 4个通配牌：需要已有1张
    if (nonWildcards.length === 1) {
      return {
        type: CardPattern.TRIPLE_WITH_PAIR,
        cards,
        power: calculateTripleWithPairPower(cards, levelCard)
      }
    }
  } else if (wildcardCount === 5) {
    // 5个通配牌：全是通配牌，可以组成三带二
    return {
      type: CardPattern.TRIPLE_WITH_PAIR,
      cards,
      power: calculateTripleWithPairPower(cards, levelCard)
    }
  }

  return null
}

/**
 * 检查连对 (掼蛋规则)
 */
function checkPairStraight(cards: Card[]): CardCombination | null {
  if (cards.length < 6 || cards.length % 2 !== 0) return null

  const rankCounts = getRankCounts(cards)
  const ranks = Object.keys(rankCounts).map(Number).sort((a, b) => a - b)

  // 检查是否都是对子
  for (const count of Object.values(rankCounts)) {
    if (count !== 2) return null
  }

  // 检查是否连续
  if (!isRanksContinuous(ranks)) return null

  return {
    type: CardPattern.STRAIGHT, // 连对也算顺子的一种
    cards,
    power: calculateStraightPower(cards) + 50 // 连对比普通顺子稍大
  }
}

/**
 * 检查飞机 (连续三张)
 * 支持 A-2-3 的特殊情况
 * 掼蛋规则：飞机只能是 6 张（两组三张）
 */
function checkAirplane(cards: Card[]): CardCombination | null {
  // 掼蛋规则：飞机只能是 6 张（两组三张）
  if (cards.length !== 6) return null

  const rankCounts = getRankCounts(cards)
  const ranks = Object.keys(rankCounts).map(Number)

  // 检查是否都是三张
  for (const count of Object.values(rankCounts)) {
    if (count !== 3) return null
  }

  // 必须是两组三张
  if (ranks.length !== 2) return null

  // 检查是否连续
  const sorted = [...ranks].sort((a, b) => a - b)
  if (sorted[1] !== sorted[0] + 1) return null

  return {
    type: CardPattern.STRAIGHT, // 飞机也算顺子的一种
    cards,
    power: calculateStraightPower(cards) + 100 // 飞机比连对更大
  }
}

/**
 * 检查三个rank是否连续（处理A的特殊情况）
 * 在掼蛋中，A可以作为1，所以 A-2-3 是连续的
 *
 * CardRank 枚举定义：
 * - TWO = 0 (2)
 * - THREE = 1 (3)
 * - FOUR = 2 (4)
 * - ...
 * - JACK = 9 (J)
 * - QUEEN = 10 (Q)
 * - KING = 11 (K)
 * - ACE = 12 (A)
 *
 * 合法的连续：
 * - ✅ 2-3-4: [0, 1, 2]
 * - ✅ Q-K-A: [10, 11, 12]
 * - ✅ A-2-3: [12, 0, 1] 或 [0, 1, 12] (A作为1)
 * - ❌ K-A-2: [11, 12, 0] 不合法（不能跨越）
 */
function isThreeRanksContinuous(ranks: number[]): boolean {
  if (ranks.length !== 3) return false

  const sorted = [...ranks].sort((a, b) => a - b)

  // 情况1：正常连续 (如 [0,1,2] = 2-3-4, [10,11,12] = Q-K-A)
  if (sorted[1] === sorted[0] + 1 && sorted[2] === sorted[1] + 1) {
    return true
  }

  // 情况2：A-2-3 的特殊情况
  // CardRank: TWO=0, THREE=1, ACE=12
  // sorted = [0, 1, 12] 表示 2-3-A，应该识别为 A-2-3（A作为1）
  const hasTwo = sorted.includes(0)    // TWO = 0
  const hasThree = sorted.includes(1)  // THREE = 1
  const hasAce = sorted.includes(12)   // ACE = 12

  if (hasTwo && hasThree && hasAce) {
    console.log('检测到 A-2-3 钢板（A作为1）')
    return true
  }

  return false
}

/**
 * 检查任意数量的ranks是否连续
 * 处理 A-2-3-4-... 的特殊情况（A作为1）
 */
function isRanksContinuous(ranks: number[]): boolean {
  if (ranks.length < 2) return false

  const sorted = [...ranks].sort((a, b) => a - b)

  // 情况1：正常连续检查
  let isContinuous = true
  for (let i = 1; i < sorted.length; i++) {
    if (sorted[i] !== sorted[i - 1] + 1) {
      isContinuous = false
      break
    }
  }

  if (isContinuous) return true

  // 情况2：检查是否是 A-2-3-4-... 的情况
  // 如果包含 3, 14(A), 15(2)，并且从3开始连续
  const hasAce = sorted.includes(14)
  const hasTwo = sorted.includes(15)

  if (hasAce && hasTwo && sorted[0] === 3) {
    // 检查从3开始是否连续到某个点，然后是14, 15
    // 例如：[3, 4, 5, 14, 15] 应该被识别为 A-2-3-4-5（A作为1）

    // 找到第一个不连续的位置
    let consecutiveEnd = 0
    for (let i = 1; i < sorted.length; i++) {
      if (sorted[i] === sorted[i - 1] + 1) {
        consecutiveEnd = i
      } else {
        break
      }
    }

    // 检查剩余的是否是 [14, 15] 或 [14, 15, ...]
    const remaining = sorted.slice(consecutiveEnd + 1)

    // 如果从3开始连续，并且剩余部分以14开始
    if (sorted[0] === 3 && remaining.length >= 1 && remaining[0] === 14) {
      // 检查剩余部分是否连续
      let remainingContinuous = true
      for (let i = 1; i < remaining.length; i++) {
        if (remaining[i] !== remaining[i - 1] + 1) {
          remainingContinuous = false
          break
        }
      }

      if (remainingContinuous) {
        // 验证整体长度：从3到consecutiveEnd的长度 + A开始的长度 应该等于总长度
        const expectedLength = (sorted[consecutiveEnd] - 3 + 1) + remaining.length
        if (expectedLength === sorted.length) {
          console.log('检测到 A-2-... 连对（A作为1）', sorted)
          return true
        }
      }
    }
  }

  return false
}

/**
 * 检查钢板 (两个连续三张，如 333444)
 */
function checkSteelBoard(cards: Card[]): CardCombination | null {
  if (cards.length !== 6) return null

  const rankCounts = getRankCounts(cards)
  const counts = Object.values(rankCounts)
  const uniqueRanks = Object.keys(rankCounts).length

  console.log('钢板检测:', {
    uniqueRanks,
    counts,
    rankCounts: Object.fromEntries(Object.entries(rankCounts).map(([k, v]) => [k, v]))
  })

  // 必须是两个三张：2种不同面值，每种面值恰好3张
  if (uniqueRanks === 2 && counts.length === 2 && counts.every(count => count === 3)) {
    console.log('识别为钢板')
    return {
      type: CardPattern.STEEL_BOARD,
      cards,
      power: calculateSteelBoardPower(cards, null)
    }
  }

  console.log('钢板检查失败')
  return null
}

/**
 * 检查木板 (三个连续对子，如 778899)
 */
function checkWoodBoard(cards: Card[]): CardCombination | null {
  if (cards.length !== 6) return null

  const rankCounts = getRankCounts(cards)
  const counts = Object.values(rankCounts)
  const uniqueRanks = Object.keys(rankCounts).length

  console.log('木板检测:', {
    uniqueRanks,
    counts,
    rankCounts: Object.fromEntries(Object.entries(rankCounts).map(([k, v]) => [k, v]))
  })

  // 必须是三个对子：3种不同面值，每种面值恰好2张
  if (uniqueRanks === 3 && counts.length === 3 && counts.every(count => count === 2)) {
    // 检查是否连续
    const ranks = Object.keys(rankCounts).map(Number)
    console.log('木板rank检查:', ranks)

    // 使用新的连续性检查函数
    const isContinuous = isThreeRanksContinuous(ranks)

    console.log('木板连续性检查:', isContinuous)

    if (isContinuous) {
      console.log('识别为木板')
      return {
        type: CardPattern.WOOD_BOARD,
        cards,
        power: calculateWoodBoardPower(cards, null)
      }
    } else {
      console.log('木板不连续，拒绝出牌')
    }
  }

  console.log('木板检查失败')
  return null
}

/**
 * 检查钢板 (支持级牌配牌)
 * 钢板：两个连续三张，如 333444
 */
function checkSteelBoardWithLevel(cards: Card[], levelCard?: Card | null): CardCombination | null {
  if (cards.length !== 6) return null

  // 如果没有通配牌，使用普通检测
  const wildcards = cards.filter(card => isWildcard(card, levelCard))
  if (wildcards.length === 0) {
    return checkSteelBoard(cards)
  }

  const nonWildcards = cards.filter(card => !isWildcard(card, levelCard))
  const rankCounts = getRankCounts(nonWildcards)
  const counts = Object.values(rankCounts).sort((a, b) => b - a)

  console.log('钢板通配牌检测:', {
    wildcardsCount: wildcards.length,
    nonWildcardsCount: nonWildcards.length,
    counts
  })

  // 钢板是两个三张，通配牌可以配成三张
  // 需要的三张数 = 2
  // 已有的三张数 + 可以用通配牌配成的三张数 >= 2

  const tripleCount = counts.filter(c => c >= 3).length
  const pairCount = counts.filter(c => c === 2).length
  const singleCount = counts.filter(c => c === 1).length

  // 通配牌可以：
  // 1. 和对子配成三张 (需要1个通配牌)
  // 2. 和单张配成三张 (需要2个通配牌)
  // 3. 三个通配牌配成一个三张

  let remainingWildcards = wildcards.length
  let totalTriples = tripleCount

  // 先用通配牌和对子配
  const triplesFromPairs = Math.min(pairCount, remainingWildcards)
  totalTriples += triplesFromPairs
  remainingWildcards -= triplesFromPairs

  // 再用通配牌和单张配
  const triplesFromSingles = Math.min(singleCount, Math.floor(remainingWildcards / 2))
  totalTriples += triplesFromSingles
  remainingWildcards -= triplesFromSingles * 2

  // 最后通配牌自己配
  const triplesFromWildcards = Math.floor(remainingWildcards / 3)
  totalTriples += triplesFromWildcards

  if (totalTriples >= 2) {
    console.log('通配牌可以配成钢板')
    return {
      type: CardPattern.STEEL_BOARD,
      cards,
      power: calculateSteelBoardPower(cards, levelCard)
    }
  }

  return null
}

/**
 * 检查木板连续性
 * 确保通配牌配牌后能形成三个连续的对子
 */
function checkWoodBoardContinuity(nonWildcards: Card[], wildcards: Card[], levelCard: Card | null): boolean {
  if (!levelCard || wildcards.length === 0) return true

  // 获取非通配牌的rank统计
  const rankCounts = getRankCounts(nonWildcards)
  const nonWildcardRanks = Object.keys(rankCounts).map(Number).sort((a, b) => a - b)

  console.log('检查钢板连续性:', {
    nonWildcardRanks,
    wildcardsCount: wildcards.length,
    rankCounts: Object.fromEntries(Object.entries(rankCounts).map(([k, v]) => [k, v]))
  })

  // 如果非通配牌已经形成连续序列，检查通配牌是否能补齐
  if (nonWildcardRanks.length >= 2) {
    // 检查非通配牌是否已经连续（包括 A-2-3 的特殊情况）
    let isContinuous = false

    if (nonWildcardRanks.length === 3) {
      // 如果已经有3个不同的rank，使用 isThreeRanksContinuous 检查
      isContinuous = isThreeRanksContinuous(nonWildcardRanks)
    } else {
      // 如果只有2个rank，检查是否连续
      isContinuous = true
      for (let i = 1; i < nonWildcardRanks.length; i++) {
        if (nonWildcardRanks[i] !== nonWildcardRanks[i - 1] + 1) {
          isContinuous = false
          break
        }
      }
    }

    if (isContinuous) {
      // 非通配牌已经连续，检查通配牌是否能补齐到3个连续对子
      console.log('非通配牌连续，检查通配牌是否能补齐')

      if (nonWildcardRanks.length === 3) {
        // 已经有3个连续的rank，检查是否都是对子
        const allPairs = nonWildcardRanks.every(rank => rankCounts[rank as CardRank] >= 2)
        if (allPairs) {
          console.log('非通配牌已经是3个连续对子，直接通过')
          return true
        }

        // 检查每个rank需要多少张通配牌
        let neededWildcards = 0
        for (const rank of nonWildcardRanks) {
          const count = rankCounts[rank as CardRank] || 0
          if (count === 1) {
            neededWildcards += 1
          }
        }

        console.log('需要的通配牌数:', neededWildcards, '实际通配牌数:', wildcards.length)

        if (wildcards.length >= neededWildcards) {
          console.log('非通配牌连续，通配牌可以补齐')
          return true
        }
      } else if (nonWildcardRanks.length === 2) {
        // 只有2个连续的rank，需要通配牌补齐第3个rank
        // 检查现有的两个rank需要多少通配牌
        let neededForExisting = 0
        for (const rank of nonWildcardRanks) {
          const count = rankCounts[rank as CardRank] || 0
          if (count === 1) {
            neededForExisting += 1
          }
        }

        // 第3个rank需要2张通配牌（可以是 minRank-1 或 maxRank+1）
        const neededWildcards = neededForExisting + 2

        console.log('需要的通配牌数:', neededWildcards, '实际通配牌数:', wildcards.length)

        if (wildcards.length >= neededWildcards) {
          console.log('非通配牌连续，通配牌可以补齐')
          return true
        }
      }
    }
  }

  // 如果非通配牌不连续，检查通配牌是否能配成连续序列
  if (nonWildcardRanks.length === 0) {
    // 全是通配牌，可以配成任意连续序列
    console.log('全是通配牌，可以配成连续钢板')
    return true
  }

  if (nonWildcardRanks.length === 1) {
    // 只有一个非通配牌rank，通配牌需要配成相邻的对子
    const wildcardCount = wildcards.length

    // 通配牌可以配成 (singleRank-1, singleRank) 或 (singleRank, singleRank+1) 或 (singleRank-1, singleRank+1)
    // 需要至少4个通配牌才能配成2个对子
    if (wildcardCount >= 4) {
      console.log('单个非通配牌，通配牌可以配成相邻对子')
      return true
    }
  }

  // 其他情况：非通配牌不连续，通配牌无法配成连续序列
  console.log('非通配牌不连续，通配牌无法配成连续钢板')
  return false
}

/**
 * 检查木板 (支持级牌配牌)
 * 木板：三个连续对子，如 778899
 */
function checkWoodBoardWithLevel(cards: Card[], levelCard?: Card | null): CardCombination | null {
  if (cards.length !== 6) return null

  // 如果没有通配牌，使用普通检测
  const wildcards = cards.filter(card => isWildcard(card, levelCard))
  if (wildcards.length === 0) {
    return checkWoodBoard(cards)
  }

  const nonWildcards = cards.filter(card => !isWildcard(card, levelCard))
  const rankCounts = getRankCounts(nonWildcards)
  const counts = Object.values(rankCounts).sort((a, b) => b - a)

  console.log('木板通配牌检测:', {
    wildcardsCount: wildcards.length,
    nonWildcardsCount: nonWildcards.length,
    counts,
    nonWildcardRanks: Object.keys(rankCounts).map(Number).sort((a, b) => a - b)
  })

  // 木板是三对，通配牌可以配成对子
  // 需要的对子数 = 3
  // 已有的对子数 + 可以用通配牌配成的对子数 >= 3

  const pairCount = counts.filter(c => c >= 2).length
  const singleCount = counts.filter(c => c === 1).length

  // 通配牌可以：
  // 1. 和单张配成对子 (需要1个通配牌)
  // 2. 两个通配牌配成一对

  const pairsFromWildcards = Math.floor(wildcards.length / 2) // 通配牌自己配成的对子
  const pairsFromSingles = Math.min(singleCount, wildcards.length - pairsFromWildcards * 2) // 通配牌和单张配成的对子

  const totalPairs = pairCount + pairsFromWildcards + pairsFromSingles

  if (totalPairs >= 3) {
    // 检查通配牌配牌后是否能形成连续的对子序列
    if (checkWoodBoardContinuity(nonWildcards, wildcards, levelCard || null)) {
      console.log('通配牌可以配成连续木板')
      return {
        type: CardPattern.WOOD_BOARD,
        cards,
        power: calculateWoodBoardPower(cards, levelCard)
      }
    } else {
      console.log('通配牌配牌后无法形成连续木板')
    }
  }

  return null
}

/**
 * 计算钢板牌力 (两个连续三张，如 333444)
 * 需要考虑通配牌配牌的情况
 */
function calculateSteelBoardPower(cards: Card[], levelCard?: Card | null): number {
  // 获取非通配牌的rank统计
  const nonWildcards = cards.filter(card => !isWildcard(card, levelCard))

  if (nonWildcards.length === 0) {
    // 全是通配牌，使用最大的通配牌rank
    const rankCounts = getRankCounts(cards)
    const maxRank = Math.max(...Object.keys(rankCounts).map(Number))
    return maxRank + 700
  }

  const rankCounts = getRankCounts(nonWildcards)
  const maxRank = Math.max(...Object.keys(rankCounts).map(Number))
  return maxRank + 700 // 钢板基础分700
}

/**
 * 计算木板牌力 (三个连续对子，如 778899)
 * 需要考虑通配牌配牌的情况
 */
function calculateWoodBoardPower(cards: Card[], levelCard?: Card | null): number {
  // 获取非通配牌的rank统计
  const nonWildcards = cards.filter(card => !isWildcard(card, levelCard))

  if (nonWildcards.length === 0) {
    // 全是通配牌，使用最大的通配牌rank
    const rankCounts = getRankCounts(cards)
    const maxRank = Math.max(...Object.keys(rankCounts).map(Number))
    return maxRank + 600
  }

  const rankCounts = getRankCounts(nonWildcards)
  const maxRank = Math.max(...Object.keys(rankCounts).map(Number))
  return maxRank + 600 // 木板基础分600
}

/**
 * 掼蛋规则的牌型比较
 */
export function compareCardCombinationsGuandan(combo1: CardCombination, combo2: CardCombination): number {
  // 炸弹类型优先级最高
  const isBomb1 = combo1.type >= CardPattern.FOUR_BOMB
  const isBomb2 = combo2.type >= CardPattern.FOUR_BOMB

  if (isBomb1 && !isBomb2) return 1
  if (!isBomb1 && isBomb2) return -1

  // 天王炸 > 同花顺 > 其他炸弹 > 普通牌型
  const priority1 = getPatternPriority(combo1.type)
  const priority2 = getPatternPriority(combo2.type)

  if (priority1 !== priority2) {
    return priority1 - priority2
  }

  // 相同类型比较牌力
  return combo1.power - combo2.power
}

/**
 * 获取牌型优先级 (掼蛋规则)
 */
function getPatternPriority(pattern: CardPattern): number {
  switch (pattern) {
    case CardPattern.KING_BOMB: return 1000 // 天王炸最大
    case CardPattern.SAME_SUIT_STRAIGHT: return 900 // 同花顺
    case CardPattern.TEN_BOMB: return 890
    case CardPattern.NINE_BOMB: return 880
    case CardPattern.EIGHT_BOMB: return 870
    case CardPattern.SEVEN_BOMB: return 860
    case CardPattern.SIX_BOMB: return 850
    case CardPattern.FIVE_BOMB: return 840
    case CardPattern.FOUR_BOMB: return 830
    case CardPattern.WOOD_BOARD: return 200 // 木板
    case CardPattern.STEEL_BOARD: return 190 // 钢板
    case CardPattern.STRAIGHT: return 180 // 顺子
    case CardPattern.TRIPLE_WITH_PAIR: return 170 // 三带二
    case CardPattern.TRIPLE: return 160 // 三张
    case CardPattern.PAIR: return 150 // 对子
    case CardPattern.SINGLE: return 140 // 单张
    case CardPattern.PASS: return 0 // 过牌
    default: return 100
  }
}